<?php
/**
 * 管理员登陆
 * User: 梁晓伟  lxw11109@gmail.com
 * Date: 2017-09-05
 * Time: 10:18
 */

namespace App\Http\Controllers\Api\V1\Manager\User;


use App\Http\Controllers\Controller;
use App\Models\UserManager;
use App\Models\UserManagerLog;
use App\Models\UserManagerRole;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class LoginController extends Controller
{
    /**
     * 管理员登陆
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $data = $request->only('userName','password');
        $validator = Validator::make($data,[
            'userName'    => 'required',
            'password'    => 'required'
        ]);
        if($validator->fails()){
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }

        $data['enabledStatus'] = 1;
        $status = UserManager::select("t1.*","t2.*")
            ->from((new UserManager())->getTable().' as t1')
            ->join((new UserManagerRole())->getTable().' as t2','t1.roleId','=','t2.roleId')
            ->where($data)
            ->first();
//        return $this->apiResponse($status);
        if($status){//成功
            $managerId = $status['managerId'];
            $userName = $status['userName'];
            $ip = getIp();
            $loginTime = date("Y-m-d H:i:s");
            UserManagerLog::create(['ip'=>$ip, 'operation'=>"登陆成功",'userName'=>$userName,'managerId'=>$managerId,'createTime'=>$loginTime]);
            return $this->apiResponse($status);
        }else{//登陆失败
            return $this->apiResponse('', config('errorCode.MANAGER_LOGIN_FAILED'));
        }
    }

    public function updatePassword(Request $request)
    {
        $data = $request->only('managerId','oldPassword','newPassword');
        $validator = Validator::make($data,[
            'managerId'    => 'integer|required',
            'oldPassword'    => 'required',
            'newPassword'    => 'required'
        ]);
        if($validator->fails()){
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        //判断密码是否正确
        $status = UserManager::where(['managerId'=>$data['managerId'],'password'=>$data['oldPassword']])->first();
        if($status){//成功
            $status = UserManager::where(['managerId'=>$data['managerId']])->update(['password'=>$data['newPassword']]);
            if($status){//更新成功
                return $this->apiResponse(true);
            }else{
                return $this->apiResponse('', config('errorCode.MANAGER_UPDATE_FAILED'));
            }
        }else{//失败
            return $this->apiResponse('', config('errorCode.OLD_PASSWORD_FALSE'));
        }
    }
}